/**
 * @vencano
 * @date 2018-01-29
 * http配置
 */
import axios from 'axios'
import Storage from '../utils/storage.js'
import router from '../router'
import {
  Alert,
  Loading,
  QSpinnerGears
} from 'quasar'
// axios 配置
axios.defaults.timeout = 60000;
axios.defaults.headers = {
  'X-Requested-With': 'XMLHttpRequest',
  'Content-Type': 'application/json'
};

axios.defaults.withCredentials = true // 跨越请求需要使用凭据
const _communityUrl = global.API_PREFIX + '/community'; //针对community下的接口做loading
const _couponUrl = global.API_PREFIX + '/coupon'; //针对coupon下的接口做loading
//  http request 拦截器
axios.interceptors.request.use(
  config => {
    // if (Storage.curUser() == null) {
    //   Storage.clear();
    //   router.push('/login')
    // }
    const _url = config.url;
    if (_url) {
      if ((_url.indexOf(_communityUrl) != -1) || (_url.indexOf(_couponUrl) != -1)) {
        Loading.show({
          spinner: QSpinnerGears,
          message: '正在加载中，请稍后...',
          messageColor: 'white',
          spinnerSize: 100, // in pixels
          spinnerColor: 'amber',
        })
      } 
    }
    return config;
  },
  err => {
    return Promise.reject(err)
  })

// http response 拦截器
axios.interceptors.response.use(
  response => {
    const {status,request:{responseURL}} = response
    if (responseURL) {
      if ((responseURL.indexOf(_communityUrl) != -1) || (responseURL.indexOf(_couponUrl) != -1)) {
        if (status === 200 || status === 302) {
          Loading.hide()
        }
      } 
    }
    return response
  },
  error => {
    Loading.hide()
    const {
      response
    } = error
    if (response) {
      const {
        status
      } = response
      switch (status) {
        case 401:
          Storage.removeCuruser()
          router.replace('/login')
          // router.push('/error?code=401')
          break;
        case 403:
          router.replace('/error?code=403')
          break;
        case 404:
          router.replace('/error?code=404')
          break;
        case 504:
          const _errAlert = Alert.create({
            enter: 'bounceInRight',
            leave: 'bounceOutRight',
            color: 'warning',
            icon: 'info',
            html: `网关异常`,
            position: 'bottom'
          });
          setTimeout(() => {
            _errAlert.dismiss();
          }, 3000);
          //   router.push('/error?code=504')
          break;
        case 400:
          router.replace('/error?code=400')
          break;
      }
      if (response.data.message) {
        const _errAlert = Alert.create({
          color: 'warning',
          icon: 'info',
          html: response.data.message,
          position: 'bottom',
        });
        setTimeout(() => {
          _errAlert.dismiss();
        }, 3000);
      }
    }
    return Promise.reject(response.data)
  });

export default axios;
